<template>
  <el-dialog
    :title="this.type == 1 ? '创建标签组' : '修改标签组'"
    :visible.sync="dialogVisible"
    width="50%"
    @close="handelClose">
    <el-form :model="Form" :rules="rules" ref="fromRef" label-width="100px">
      <el-form-item label="标签组名称" prop="groupName">
        <el-input v-model="Form.groupName"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input type="textarea" v-model="Form.description"></el-input>
      </el-form-item>
      <el-form-item
        v-show="this.type === 2"
        label="资产标签"
        prop="assetsTagEntity">
        <el-tag
          class="form-tag"
          closable
          v-for="(item, i) in Form.assetsTagEntity"
          :key="i"
          :color="item.color"
          @close="deleteTag(item.id)">{{item.name}}</el-tag>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addTaggroup">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  addAssetsTags,
  getAssetsTagGroupById,
  delAssetsTags,
  editAssetsTagGroup
} from '@/api/assets/configuration.js'
export default {
  data() {
    return {
      dialogVisible: false,
      Form: {
        id: '',
        groupName: '',
        description: '',
        assetsTagEntity: []
      },
      rules: {
        groupName: [
          { required: true, message: '标签组名称', trigger: 'blur' }
        ]
      },
      id: '',
      type: ''
    }
  },
  created() {
  },
  methods: {
    init(id, type, flag) {
      this.type = type
      if (this.type === 1) {
        this.id = null
      } else {
        this.id = id
      }
      if (this.id) {
        this.getData()
      }
      this.dialogVisible = flag
    },
    // 提交表单
    addTaggroup() {
      this.$refs.fromRef.validate(valid => {
        if (!valid) return
        if (this.type === 2) { // 修改
          const data = {
            id: this.Form.id,
            groupName: this.Form.groupName,
            description: this.Form.description
          }
          editAssetsTagGroup(data).then((res) => {
            this.dialogVisible = false
            this.$emit('addTagGroup')
          })
        } else { // 新增
          const formdata = {
            groupName: this.Form.groupName,
            description: this.Form.description
          }
          addAssetsTags(formdata).then((res) => {
            this.dialogVisible = false
            this.$emit('addTagGroup')
          })
        }
      })
    },
    handelClose() {
      this.$refs.fromRef.resetFields()
    },
    getData() {
      getAssetsTagGroupById({ id: this.id }).then((res) => {
        this.Form = res.data
      })
    },
    // 删除标签
    deleteTag(id) {
      delAssetsTags(id).then((res) => {
        this.getData()
      })
    }
  }
}
</script>

<style scoped>
.form-tag {
  margin-right: 3px;
}
</style>
